#include "web.h"
#include <QLineEdit>
#include <QPushButton>
#include <QtWebKit/QWebView>
#include <QGridLayout>
#include <QFrame>
#include <QWSServer>


#define INITWEBADRESS "http://www.hao123.com"
Web::Web(QWidget *parent) : JDialog(parent)
{
    im = new InputMethod;
//    DebugOrRelease=0;
    m_pUrlEdit = new QLineEdit();
    m_pUrlEdit->setText(INITWEBADRESS);
    m_pUrlEdit->installEventFilter(im);
    m_pUrlEdit->setObjectName("m_pUrlEdit");
    connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method

    m_pWebView = new QWebView();
    m_pWebView->load(QUrl(INITWEBADRESS));
    m_pWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);


    QPushButton *pGoBtn = new QPushButton(tr("Go"));
    QPushButton *pBackBtn = new QPushButton(tr("<"));
    QGridLayout *pSubLayout = new QGridLayout();

    pSubLayout->addWidget(m_pUrlEdit, 0, 0, 1, 10);
    pSubLayout->addWidget(pBackBtn, 0, 10, 1, 1);
    pSubLayout->addWidget(pGoBtn, 0, 11, 1, 2);
    pSubLayout->addWidget(m_pWebView, 1, 0, 5, 13);
    pSubLayout->setSpacing(10);

    QFrame *pFrame = new QFrame();
    pFrame->setLayout(pSubLayout);
    pFrame->setObjectName("webFrame");

    QGridLayout *pMainLayout = new QGridLayout();
    pMainLayout->addWidget(pFrame);

    connect(pGoBtn, SIGNAL(clicked(bool)), this, SLOT(slotGoBtnClicked()));
    connect(m_pWebView, SIGNAL(loadFinished(bool)), this, SLOT(slotCheckLoad(bool)));
    connect(m_pWebView, SIGNAL(urlChanged(QUrl)), this, SLOT(slotUrlChanged(QUrl)));
    connect(m_pWebView, SIGNAL(linkClicked(QUrl)), this, SLOT(slotLinkClicked(QUrl)));
    connect(pBackBtn, SIGNAL(clicked(bool)), m_pWebView, SLOT(back()));
    if (DebugOrRelease)
    this->setCursor(Qt::CrossCursor);
    this->setJLayout(pMainLayout);
    this->setJTitle(tr("浏览器"));
}

void Web::createImConnect(QString ObjName)
{
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pUrlEdit,SLOT(setText(QString)));

    if(ObjName=="m_pUrlEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pUrlEdit,SLOT(setText(QString)));
}

void Web::slotGoBtnClicked()
{
    m_pWebView->load(QUrl(m_pUrlEdit->text()));
}

void Web::slotLinkClicked(QUrl url)
{
    m_pWebView->load(url);
}

void Web::slotCheckLoad(bool isLoad)
{
    if(isLoad) {
        //"load success");
    }
    else {
        //"load fail");
    }
}

void Web::slotUrlChanged(QUrl url)
{
    m_pUrlEdit->setText(url.toString());
}

Web::~Web()
{
	if(!DebugOrRelease)
	{
		QApplication::setOverrideCursor(Qt::BlankCursor); 
		QWSServer::setCursorVisible(false);
	}

}



